package com.hibase.core.mybatis.registrar;

import cn.hutool.core.collection.CollUtil;
import com.hibase.core.mybatis.annotation.HibaseMapperScan;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 扫描mapper文件所在包
 *
 * @author hufeng
 * @date 2019/05/21
 */
@Slf4j
public class MapperClassRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {

        AnnotationAttributes mapperScanAttrs = AnnotationAttributes
                .fromMap(annotationMetadata.getAnnotationAttributes(HibaseMapperScan.class.getName()));
        if (mapperScanAttrs != null) {
            registerBeanDefinitions(mapperScanAttrs, beanDefinitionRegistry);
        }
    }

    void registerBeanDefinitions(AnnotationAttributes annoAttrs, BeanDefinitionRegistry registry) {

        List<String> basePackages = new ArrayList<>();

        basePackages.addAll(
                Arrays.stream(annoAttrs.getStringArray("basePackages"))
                        .filter(StringUtils::hasText)
                        .collect(Collectors.toList()));

        MapperClassScanner scan = new MapperClassScanner(registry);

        Set<BeanDefinitionHolder> beanDefinitionHolders = scan.doScan(StringUtils.toStringArray(basePackages));

        if (CollUtil.isNotEmpty(beanDefinitionHolders)) {

            for (BeanDefinitionHolder definitionHolder : beanDefinitionHolders) {

                log.info("测试内容：{}", definitionHolder.getBeanName());
            }
        }
    }
}
